import WebIM from '@/easemob/web-im';

const chat = {
    state: {
        // 连接成功标识
        isConnSuccess: false,
        // 所有消息 username:msgList
        msgObj: {},
        // 好友列表
        friendList: [],
        // 新消息
        newMessage: {},
        // 未读消息 username:msgIdList
        unReadMsgObj: {}
    },
    mutations: {
        SET_WEB_IM_CONN_STATE: (state, flag) => {
            state.isConnSuccess = flag;
        },
        SET_WEB_IM_FRIEND_LIST: (state, list) => {
            state.friendList = list;
        },
        SET_WEB_IM_MESSAGE: (state, msg) => {
            // 存储新消息到历史
            let msgList = state.msgObj[msg.username];
            if (!msgList) {
                msgList = [];
                state.msgObj[msg.username] = msgList;
            }
            msgList.push(msg);

            // 存储未读消息id
            let unReadMsgIdList = state.unReadMsgObj[msg.username];
            if (!unReadMsgIdList) {
                unReadMsgIdList = [];
                state.unReadMsgObj[msg.username] = unReadMsgIdList;
            }
            unReadMsgIdList.push(msg.id);

            state.newMessage = msg;
        },
        RESET_UNREAD_COUNT: (state, username) => {
            state.unReadMsgObj[username] = [];
        }
    },
    actions: {
        // 好友列表
        getWebImFriendList ({commit}) {
            return new Promise((resolve, reject) => {
                WebIM.conn.getRoster({
                    success: function (roster) {
                        let friendList = [];
                        if (roster && roster.length > 0) {
                            roster.forEach(item => {
                                friendList.push({ name: item.name });
                            });
                            commit('SET_WEB_IM_FRIEND_LIST', friendList);
                        }
                        resolve(friendList);
                    }
                });
            });
        },
        // 消息已读
        readWebImMsg ({commit, state}, username) {
            return new Promise((resolve, reject) => {
                let msgIdList = state.unReadMsgObj[username];
                if (msgIdList && msgIdList.length > 0) {
                    msgIdList.forEach(item => {
                        let msg = new WebIM.message(WebIM.msgType.read.value, WebIM.conn.getUniqueId());
                        msg.set({
                            id: item,
                            to: username
                        });
                        WebIM.conn.send(msg.body);
                    });
                    commit('RESET_UNREAD_COUNT', username);
                }
                resolve();
            });
        },
        // 发送文本
        sendWebImText ({commit}, { to, content }) {
            return new Promise((resolve, reject) => {
                let msg = new WebIM.message(WebIM.msgType.txt.value, WebIM.conn.getUniqueId());
                msg.set({
                    msg: content,
                    to,
                    roomType: false,
                    success: function (id, msgId) {
                        commit('SET_WEB_IM_MESSAGE', {id: msgId, isSelf: true, type: WebIM.msgType.txt.value, username: to, content});
                        resolve();
                    },
                    fail: function (err) {
                        console.log(err);
                        reject(err);
                    }
                });
                WebIM.conn.send(msg.body);
            });
        },
        // 发送文件
        sendWebImFile ({commit}, { type, to, fileInput }) {
            return new Promise((resolve, reject) => {
                let msg = new WebIM.message(type, WebIM.conn.getUniqueId());
                let file = WebIM.utils.getFileUrl(fileInput);
                let apiUrl = WebIM.config.apiURL;
                let fileUploadCompleteUrl = '';
                let option = {
                    apiUrl,
                    file,
                    to,
                    roomType: false,
                    // 上传文件失败
                    onFileUploadError: function (err) {
                        console.log(err);
                        reject(err);
                    },
                    // 上传文件完成
                    onFileUploadComplete: function (data) {
                        fileUploadCompleteUrl = data.uri + '/' + data.entities[0].uuid;
                    },
                    success: function (id, msgId) {
                        commit('SET_WEB_IM_MESSAGE', {id: msgId, type, isSelf: true, username: to, content: fileUploadCompleteUrl});
                        resolve();
                    }
                };
                msg.set(option);
                WebIM.conn.send(msg.body);
            });
        }
    }
};

export default chat;
